package com.ship.dispatch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchPotentialScheme;
import com.ship.dispatch.bean.SpDispatchPotentialSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bo.HistoryDispatchBO;
import com.ship.dispatch.bo.SpDispatchSchemeDetailBO;
import com.ship.dispatch.model.SpDispatchSchemeSaveModel;
import com.ship.dispatch.model.dto.DispatchPotentialSchemeChartSaveDto;
import com.ship.dispatch.model.dto.DispatchSchemeChartSaveDto;
import com.ship.dispatch.model.dto.SchemeChartSellDto;
import com.ship.dispatch.model.dto.SchemeChartSimpleDto;
import com.ship.dispatch.service.*;
import com.ship.dispatch.vo.SpDispatchSchemeDetailExVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

/**
 * 调度优化潜在投标 前端控制器
 *
 * @author AbyssRabbit@163.com
 * @since 2023-10-17
 */
@RestController
@RequestMapping("/spDispatch/potential/")
@Api(value = "disSpDispatchPotential", tags = "调度优化潜在投标前端控制器")
public class SpDispatchPotentialController {

    @Autowired
    private SpDispatchPotentialService spDispatchService;

    @Autowired
    private SpDispatchPotentialSchemeDetailService dispatchPotentialSchemeDetailService;

    @Autowired
    private ExportService exportService;

    /**
     * 新增调度方案信息
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增调度方案信息")
    @PostMapping("scheme/save")
    @Log(title = "新增调度方案信息",businessType = BusinessType.INSERT)
    public JsonResult schemeSave(@RequestBody SpDispatchSchemeSaveModel dto) {
        return dispatchPotentialSchemeDetailService.schemeSave(dto);
    }

    /**
     * 最新调度数据同步至潜在投标
     *
     * @return
     */
    @ApiOperation(value = "最新调度数据同步至潜在投标")
    @GetMapping("data/update")
    public JsonResult dataUpdate() {
        return dispatchPotentialSchemeDetailService.dataUpdate();
    }

    /**
     * 贸易利润率参数更改
     *
     * @param detail
     * @return
     */
    @ApiOperation(value = "贸易利润率参数更改")
    @PostMapping("tradingProfit/update")
    public JsonResult<SpDispatchPotentialSchemeDetail> tradingProfitUpdate(@RequestBody SpDispatchPotentialSchemeDetail detail) {
        return spDispatchService.tradingProfitUpdate(detail);
    }

    /**
     * 获取调度优化方案甘特图信息
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案甘特图信息")
    @PostMapping("scheme/chart")
    public JsonResult<SpDispatchPotentialSchemeDetail> getPlanSchemeChart(@RequestBody SchemeChartSimpleDto dto) {
        return spDispatchService.getPlanSchemeChart(dto);
    }

    /**
     * 调度方案绑定销售合同、补货
     *
     * @return
     */
    @ApiOperation(value = "调度方案绑定销售合同、补货")
    @PostMapping("scheme/sell")
    public JsonResult schemeSell(@RequestBody @Validated SchemeChartSellDto dto) {
        return spDispatchService.schemeSell(dto);
    }

    /**
     * 甘特图拖拽保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖拽保存")
    @PostMapping("scheme/chart/save")
    public JsonResult schemeChartSave( @RequestBody @Validated DispatchPotentialSchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getStringUserId());
        return dispatchPotentialSchemeDetailService.schemeChartSave(dto);
    }

    /**
     * 甘特图拖动关联信息计算保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖动关联信息计算保存")
    @PostMapping("scheme/chart/calculate/save")
    public JsonResult schemeChartCalculateSave( @RequestBody @Validated DispatchPotentialSchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getStringUserId());
        return dispatchPotentialSchemeDetailService.schemeChartCalculateSave(dto);
    }

    /**
     * 获取调度优化方案调度历史
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案调度历史")
    @PostMapping("scheme/history")
    public JsonResult<List<SpDispatchPotentialSchemeDetail>> getSchemeHistory(@RequestBody HistoryDispatchBO historyDispatchBO) {
        return spDispatchService.getSchemeHistory(historyDispatchBO);
    }

    /**
     * 调度优化方案还原
     *
     * @return
     */
    @ApiOperation(value = "调度优化方案还原")
    @GetMapping("scheme/rollback/{schemeId}")
    @Log(title = "调度优化方案还原",businessType = BusinessType.UPDATE)
    public JsonResult schemeRollback(@PathVariable(value = "schemeId") String schemeId) {
        return spDispatchService.schemeRollback(schemeId);
    }

    /**
     * 根据方案详情ID获取变更历史记录
     *
     * @return
     */
    @ApiOperation(value = "根据方案详情ID获取变更历史记录")
    @PostMapping("scheme/detail/history")
    public JsonResult<List<SpDispatchPotentialSchemeDetail>> getSchemeDetailHistory(@RequestBody @Validated SchemeChartSimpleDto dto) {
        return spDispatchService.getSchemeDetailHistory(dto);
    }

    /**
     * 获取调度优化方案详情分页
     *
     * @return
     */
    @ApiOperation(value = "获取调度优化方案详情分页")
    @PostMapping("scheme/detail/page")
    public JsonResult<Object> getSchemeDetailPage(@RequestBody @Validated SpDispatchPotentialSchemeDetail dto) {
        return spDispatchService.getSchemeDetailPage(dto);
    }

    /**
     * 修改方案详情
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "修改方案详情")
    @PostMapping("scheme/detail/update")
    @Log(title = "修改方案详情",businessType = BusinessType.UPDATE)
    public JsonResult schemeDetailUpdate(@RequestBody SpDispatchSchemeDetailBO dto) {
        return dispatchPotentialSchemeDetailService.schemeDetailUpdate(dto);
    }

    /**
     * 删除方案详情
     *
     * @param detailId
     * @param reasonMsg
     * @return
     */
    @ApiOperation(value = "删除方案详情")
    @DeleteMapping("scheme/detail/delete")
    @Log(title = "删除方案详情",businessType = BusinessType.DELETE)
    public JsonResult schemeDetailDelete(@RequestParam(value = "detailId") Long detailId, @RequestParam(value = "reasonMsg") String reasonMsg) {
        return dispatchPotentialSchemeDetailService.schemeDetailDelete(detailId,reasonMsg);
    }



    @ApiOperation(value = "导出调度方案列表")
    @PostMapping("scheme/exportDispatchPlan")
    @Log(title = "导出调度方案列表",businessType = BusinessType.EXPORT)
    public JsonResult<Object> exportDispatchPlan(@RequestBody SpDispatchPotentialSchemeDetail dto) {
        //获取最新的方案信息
        SpDispatchPotentialScheme spDispatchScheme = spDispatchService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpDispatchPotentialScheme>()
                        .eq(SpDispatchPotentialScheme::getIsHistory,0)
                        .eq(SpDispatchPotentialScheme::getIsHistory,0)
                        .eq(dto.getSchemeId() != null,SpDispatchPotentialScheme::getId,dto.getSchemeId())
                        .and(qw -> {
                            qw.eq(SpDispatchPotentialScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpDispatchPotentialScheme::getIsShare,1);
                        })
                        .orderByDesc(SpDispatchPotentialScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spDispatchScheme == null){
            return JsonResult.success(new Page<>());
        }
        dto.setSchemeId(spDispatchScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheme_id",spDispatchScheme.getId());
        queryWrapper.orderByDesc("expected_loading_date");
        List<SpDispatchPotentialSchemeDetail> exportList = dispatchPotentialSchemeDetailService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpDispatchPotentialSchemeDetail spDispatchSchemeDetail : exportList) {
            spDispatchSchemeDetail.setTradeBodyStr(spDispatchSchemeDetail.getTradeBodyStr());
            spDispatchSchemeDetail.setSellerTradeBodyStr(spDispatchSchemeDetail.getSellerTradeBodyStr());
            spDispatchSchemeDetail.setTradeTypeStr(spDispatchSchemeDetail.getTradeTypeStr());
            spDispatchSchemeDetail.setSellerTradeTypeStr(spDispatchSchemeDetail.getSellerTradeTypeStr());
        }
        Field[] fields = SpDispatchSchemeDetail.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_dispatch_scheme_detail",SecurityUtils.getUserId()), "调度优化方案详情信息");
        return JsonResult.success(url);
    }

    @ApiOperation(value = "导出调度方案列表")
    @PostMapping("scheme/exportDispatchPlanAndGante")
    public JsonResult<Object> exportDispatchPlanAndGante(@RequestBody SpDispatchSchemeDetailExVo spDispatchSchemeDetailExVo) {
        SpDispatchPotentialSchemeDetail dto = new SpDispatchPotentialSchemeDetail();
        dto.setIds(spDispatchSchemeDetailExVo.getIds());
        dto.setSeller(spDispatchSchemeDetailExVo.getSeller());

        //获取最新的方案信息
        SpDispatchPotentialScheme spDispatchScheme = spDispatchService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpDispatchPotentialScheme>()
                        .eq(SpDispatchPotentialScheme::getIsHistory,0)
                        .and(qw -> {
                            qw.eq(SpDispatchPotentialScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpDispatchPotentialScheme::getIsShare,1);
                        })
                        .orderByDesc(SpDispatchPotentialScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spDispatchScheme == null){
            return JsonResult.success(new Page<>());
        }
        dto.setSchemeId(spDispatchScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheme_id",spDispatchScheme.getId());
        queryWrapper.orderByDesc("expected_loading_date");

        List<SpDispatchPotentialSchemeDetail> exportList = dispatchPotentialSchemeDetailService.pageExportList(dto, queryWrapper, new LinkedList<>());
        for (SpDispatchPotentialSchemeDetail spDispatchSchemeDetail : exportList) {
            spDispatchSchemeDetail.setTradeBodyStr(spDispatchSchemeDetail.getTradeBodyStr());
            spDispatchSchemeDetail.setSellerTradeBodyStr(spDispatchSchemeDetail.getSellerTradeBodyStr());
            spDispatchSchemeDetail.setTradeTypeStr(spDispatchSchemeDetail.getTradeTypeStr());
            spDispatchSchemeDetail.setSellerTradeTypeStr(spDispatchSchemeDetail.getSellerTradeTypeStr());
        }
        Field[] fields = SpDispatchSchemeDetail.class.getDeclaredFields();
        String fileUrl = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_dispatch_scheme_detail",SecurityUtils.getUserId()), "调度优化方案详情信息");
        String url = spDispatchService.exportDispatchPlanAndGante(spDispatchSchemeDetailExVo,fileUrl);
        return JsonResult.success(url);
    }

}
